package me.alide.modules.sys.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import me.alide.common.exception.RRException;
import me.alide.common.utils.PageUtils;
import me.alide.common.utils.R;
import me.alide.modules.survey.form.SurveyDetail;
import me.alide.modules.sys.entity.InformationEntity;
import me.alide.modules.sys.service.InformationService;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import static me.alide.common.utils.Constant.DATA;

@Slf4j
@RestController
@RequestMapping("/sys/info")
public class InformationController {
    @Autowired
    private InformationService informationService;

    /**
     * 查询所有
     *
     * @return
     */
    @GetMapping("queryAll")
    public R queryAll() {
        try {
            List<InformationEntity> list = informationService.queryAll();
            return R.ok().put(DATA, list);
        } catch (Exception e) {
            log.error("查询失败", e);
            return R.error();
        }

    }

    @RequestMapping("show")
    public R show(Integer page, Integer pageSize) {
        if (page == null) {
            page = 1;
        }
        IPage<InformationEntity> informationEntityIPage = informationService.show(page, 10);
        return R.ok().put(DATA, informationEntityIPage);
    }

    /**
     *
     * @param params  分页
     * @return
     */

    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = informationService.query(params);
        return R.ok().put("page", page);
    }

    /**
     *
     * @param info  添加
     * @return
     */
    @RequestMapping("/save")
    public R savaInfo(@RequestBody InformationEntity info) {
        try {
            int sava = informationService.saveInfo(info);
            if (sava == 1) {
                log.info("添加成功");
            } else {
                throw new RRException("添加失败", 500);
            }
        } catch (Exception e) {
            log.error("保存失败", e);
            return R.error(500, e.getMessage());
        }
        return R.ok();
    }

    /**
     *
     * @param ids  删除
     * @return
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        try {
            int deleteCount = informationService.delete(ids);
            if (deleteCount == 1) {
                log.info("删除成功 {} 条", deleteCount);
            } else {
                throw new RRException("删除失败", 500);
            }
        } catch (Exception e) {
            log.error("删除失败", e);
            return R.error(500, e.getMessage());
        }
        return R.ok();
    }

    /**
     *
     * @param info  修改
     * @return
     */
    @RequestMapping("/update")
    public R update(@RequestBody InformationEntity info) {
        try {
            int update = informationService.update(info);
            if (update == 1) {

                log.info("修改成功");
            } else {
                log.error("修改失败", 500);
            }
        } catch (Exception e) {
            log.error("修改失败", e);
            return R.error(500, e.getMessage());
        }
        return R.ok();
    }

    /**
     *  根据id查
     */
    @GetMapping("/info/{id}")
     public R info(@PathVariable("id") Long id ){
         InformationEntity info= informationService.getById(id);
         return R.ok().put("info",info);
     }
     @GetMapping("/query")
     public void query(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<InformationEntity> list =informationService.queryAll();
         POIFSFileSystem fs = new POIFSFileSystem(this.getClass().getClassLoader().getResourceAsStream("excel/info"));
         HSSFWorkbook wb = new HSSFWorkbook(fs);
         HSSFSheet sheet = wb.getSheetAt(0);
         sheet.setForceFormulaRecalculation(true);
         fillExcel(list,sheet,wb);
         String fileName="企业信息清单";
         response.reset();
         response.setCharacterEncoding("UTF-8");
         String header = request.getHeader("User-Agent").toUpperCase();
         if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
             fileName = URLEncoder.encode(fileName, "utf-8");
             fileName = fileName.replace("+", "%20");
         } else {
             fileName = new String(fileName.getBytes(), "utf-8");
         }
         response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
         response.setContentType("application/vnd.ms-excel");
         // 直接用数组缓冲输出流输出
         wb.write(response.getOutputStream());
     }
    private void fillExcel(List<InformationEntity> list, HSSFSheet sheet, HSSFWorkbook workbook){
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        for (int i=0;i<list.size();i++) {
            InformationEntity informationEntity = list.get(i);
            Row row = sheet.createRow(i + 5);
            for (int j = 0; j < 50; j++) {
                Cell cell = row.createCell(j);
                cell.setCellStyle(cellStyle);
            }

            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getId());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getUserId());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getDutyUserName());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getOrgName());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getOrgAdd());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getBusiness());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getSpecial());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getLeader());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getStatus());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getRegCapital());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getContact());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getContactJob());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getContactPhone());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getDept());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getLeader());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getLeaderJob());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getLeaderPhone());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getLeaderContact());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getLeaderContactJob());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getLeaderContactPhone());
            sheet.getRow(i + 5).getCell(0).setCellValue(informationEntity.getCreateTime());
        }
        }
}
